<?php
namespace app\admin\controller;

use app\admin\model\Admin;
use think\facade\Db;

class Account extends \app\BaseController
{
    /**
     * 账号管理页面
     */
    public function index()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return redirect('/admin/login');
        }
        
        // 获取查询参数
        $keyword = $this->request->param('keyword', '');
        $status = $this->request->param('status', '');
        $role = $this->request->param('role', '');
        $page = $this->request->param('page', 1);
        $limit = 15;
        
        // 构建查询条件
        $where = [];
        if (!empty($keyword)) {
            $where[] = ['username|nickname|email', 'like', '%' . $keyword . '%'];
        }
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        if (!empty($role)) {
            $where[] = ['role', '=', $role];
        }
        
        try {
            // 获取管理员列表
            $admins = Admin::where($where)
                          ->order('create_time', 'desc')
                          ->paginate([
                              'list_rows' => $limit,
                              'page' => $page
                          ]);
            
            // 获取统计数据
            $statistics = [
                'total' => Admin::count(),
                'active' => Admin::where('status', 1)->count(),
                'inactive' => Admin::where('status', 0)->count(),
                'super_admin' => Admin::where('role', 'super_admin')->count(),
                'admin' => Admin::where('role', 'admin')->count(),
            ];
            
        } catch (\Exception $e) {
            $admins = [];
            $statistics = [
                'total' => 0,
                'active' => 0,
                'inactive' => 0,
                'super_admin' => 0,
                'admin' => 0,
            ];
        }
        
        // 准备视图数据
        $data = [
            'title' => '账号管理',
            'current_menu' => 'account',
            'admins' => $admins,
            'statistics' => $statistics,
            'keyword' => $keyword,
            'status' => $status,
            'role' => $role,
            'admin_user' => $_SESSION['admin_user']
        ];
        
        return view('account/index', $data);
    }
    
    /**
     * 添加管理员
     */
    public function add()
    {
        if ($this->request->isPost()) {
            return $this->doAdd();
        }
        
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return redirect('/admin/login');
        }
        
        // 准备视图数据
        $data = [
            'title' => '添加管理员',
            'current_menu' => 'account',
            'admin_user' => $_SESSION['admin_user']
        ];
        
        return view('account/add', $data);
    }
    
    /**
     * 执行添加管理员
     */
    public function doAdd()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $username = trim($this->request->post('username'));
        $password = $this->request->post('password');
        $password_confirm = $this->request->post('password_confirm');
        $nickname = trim($this->request->post('nickname'));
        $email = trim($this->request->post('email'));
        $role = $this->request->post('role', 'admin');
        $status = $this->request->post('status') ? 1 : 0;
        
        // 验证参数
        $errors = [];
        
        if (empty($username)) {
            $errors['username'] = '用户名不能为空';
        } elseif (strlen($username) < 3) {
            $errors['username'] = '用户名至少3个字符';
        } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
            $errors['username'] = '用户名只能包含字母、数字和下划线';
        }
        
        if (empty($password)) {
            $errors['password'] = '密码不能为空';
        } elseif (strlen($password) < 6) {
            $errors['password'] = '密码至少6个字符';
        }
        
        if ($password !== $password_confirm) {
            $errors['password_confirm'] = '两次输入的密码不一致';
        }
        
        if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = '邮箱格式不正确';
        }
        
        // 权限检查：只有超级管理员才能创建超级管理员
        $currentUser = $_SESSION['admin_user'];
        if ($role === 'super_admin' && $currentUser['role'] !== 'super_admin') {
            $errors['role'] = '只有超级管理员才能创建超级管理员';
        }
        
        if (!empty($errors)) {
            return json(['code' => 0, 'msg' => '验证失败', 'errors' => $errors]);
        }
        
        try {
            // 检查用户名是否已存在
            $existAdmin = Admin::where('username', $username)->find();
            if ($existAdmin) {
                return json(['code' => 0, 'msg' => '用户名已存在']);
            }
            
            // 检查邮箱是否已存在
            if (!empty($email)) {
                $existEmail = Admin::where('email', $email)->find();
                if ($existEmail) {
                    return json(['code' => 0, 'msg' => '邮箱已被使用']);
                }
            }
            
            // 创建管理员
            $admin = new Admin();
            $admin->username = $username;
            $admin->password = $password; // 模型中会自动加密
            $admin->nickname = $nickname ?: $username;
            $admin->email = $email;
            $admin->role = $role;
            $admin->status = $status;
            $admin->save();
            
            // 记录操作日志
            $this->addLog('add_admin', "添加管理员：{$username}，角色：{$role}", $admin->id);
            
            return json(['code' => 1, 'msg' => '添加成功', 'url' => '/admin/account']);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '添加失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 编辑管理员
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            return $this->doEdit();
        }
        
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return redirect('/admin/login');
        }
        
        $id = $this->request->param('id');
        
        try {
            $admin = Admin::find($id);
            if (!$admin) {
                return redirect('/admin/account')->with('error', '管理员不存在');
            }
        } catch (\Exception $e) {
            return redirect('/admin/account')->with('error', '查询失败');
        }
        
        // 准备视图数据
        $data = [
            'title' => '编辑管理员',
            'current_menu' => 'account',
            'admin' => $admin,
            'admin_user' => $_SESSION['admin_user']
        ];
        
        return view('account/edit', $data);
    }
    
    /**
     * 执行编辑管理员
     */
    public function doEdit()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $id = $this->request->param('id');
        $password = $this->request->post('password');
        $password_confirm = $this->request->post('password_confirm');
        $nickname = trim($this->request->post('nickname'));
        $email = trim($this->request->post('email'));
        $role = $this->request->post('role', 'admin');
        $status = $this->request->post('status') ? 1 : 0;
        
        try {
            $admin = Admin::find($id);
            if (!$admin) {
                return json(['code' => 0, 'msg' => '管理员不存在']);
            }
            
            $currentUser = $_SESSION['admin_user'];
            
            // 验证参数
            $errors = [];
            
            if (!empty($password)) {
                if (strlen($password) < 6) {
                    $errors['password'] = '密码至少6个字符';
                }
                
                if ($password !== $password_confirm) {
                    $errors['password_confirm'] = '两次输入的密码不一致';
                }
                
                // 权限检查：只有超级管理员才能修改超级管理员的密码
                if ($admin->role === 'super_admin' && $currentUser['role'] !== 'super_admin') {
                    $errors['password'] = '只有超级管理员才能修改超级管理员的密码';
                }
            }
            
            if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $errors['email'] = '邮箱格式不正确';
            }
            
            // 权限检查：只有超级管理员才能修改超级管理员的角色
            if ($admin->role === 'super_admin' && $currentUser['role'] !== 'super_admin' && $role !== $admin->role) {
                $errors['role'] = '只有超级管理员才能修改超级管理员的权限级别';
            }
            
            // 权限检查：只有超级管理员才能创建超级管理员
            if ($role === 'super_admin' && $currentUser['role'] !== 'super_admin') {
                $errors['role'] = '只有超级管理员才能设置超级管理员权限';
            }
            
            // 不能禁用自己
            if ($id == $currentUser['id'] && $status == 0) {
                $errors['status'] = '不能禁用自己的账号';
            }
            
            // 超级管理员不能被禁用
            if ($admin->role === 'super_admin' && $status == 0) {
                $errors['status'] = '超级管理员账号不能被禁用';
            }
            
            if (!empty($errors)) {
                return json(['code' => 0, 'msg' => '验证失败', 'errors' => $errors]);
            }
            
            // 检查邮箱是否已被其他用户使用
            if (!empty($email) && $email !== $admin->email) {
                $existEmail = Admin::where('email', $email)->where('id', '<>', $id)->find();
                if ($existEmail) {
                    return json(['code' => 0, 'msg' => '邮箱已被其他用户使用']);
                }
            }
            
            // 更新信息
            if (!empty($password)) {
                $admin->password = $password; // 模型中会自动加密
            }
            
            $admin->nickname = $nickname ?: $admin->username;
            $admin->email = $email;
            $admin->role = $role;
            $admin->status = $status;
            $admin->save();
            
            // 如果修改的是当前用户，更新session
            if ($id == $currentUser['id']) {
                $_SESSION['admin_user']['nickname'] = $admin->nickname;
                $_SESSION['admin_user']['email'] = $admin->email;
                $_SESSION['admin_user']['role'] = $admin->role;
            }
            
            // 记录操作日志
            $this->addLog('edit_admin', "编辑管理员：{$admin->username}", $id);
            
            return json(['code' => 1, 'msg' => '修改成功', 'url' => '/admin/account']);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '修改失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除管理员
     */
    public function delete()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $id = $this->request->param('id');
        $currentUser = $_SESSION['admin_user'];
        
        try {
            $admin = Admin::find($id);
            if (!$admin) {
                return json(['code' => 0, 'msg' => '管理员不存在']);
            }
            
            // 不能删除自己
            if ($id == $currentUser['id']) {
                return json(['code' => 0, 'msg' => '不能删除自己的账号']);
            }
            
            // 超级管理员不能被删除
            if ($admin->role === 'super_admin') {
                return json(['code' => 0, 'msg' => '超级管理员账号不能被删除']);
            }
            
            $username = $admin->username;
            $admin->delete();
            
            // 记录操作日志
            $this->addLog('delete_admin', "删除管理员：{$username}", $id);
            
            return json(['code' => 1, 'msg' => '删除成功']);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 修改状态
     */
    public function changeStatus()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $id = $this->request->param('id');
        $status = $this->request->post('status');
        $currentUser = $_SESSION['admin_user'];
        
        try {
            $admin = Admin::find($id);
            if (!$admin) {
                return json(['code' => 0, 'msg' => '管理员不存在']);
            }
            
            // 不能禁用自己
            if ($id == $currentUser['id'] && $status == 0) {
                return json(['code' => 0, 'msg' => '不能禁用自己的账号']);
            }
            
            // 超级管理员不能被禁用
            if ($admin->role === 'super_admin' && $status == 0) {
                return json(['code' => 0, 'msg' => '超级管理员账号不能被禁用']);
            }
            
            $admin->status = $status;
            $admin->save();
            
            $statusText = $status == 1 ? '启用' : '禁用';
            
            // 记录操作日志
            $this->addLog('change_admin_status', "{$statusText}管理员：{$admin->username}", $id);
            
            return json(['code' => 1, 'msg' => $statusText . '成功']);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '操作失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 记录操作日志
     */
    private function addLog($action, $description, $target_id = 0)
    {
        try {
            $adminUser = $_SESSION['admin_user'];
            Db::name('admin_log')->insert([
                'admin_id' => $adminUser['id'],
                'admin_name' => $adminUser['username'],
                'action' => $action,
                'description' => $description,
                'target_id' => $target_id,
                'ip' => $this->request->ip(),
                'user_agent' => $this->request->header('User-Agent'),
                'create_time' => time()
            ]);
        } catch (\Exception $e) {
            // 日志记录失败不影响主要功能
        }
    }
}
